package com.swang.pms.web.controller.manage;

import java.util.Date;
import java.util.Iterator;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.swang.pms.common.util.EnumToDataUtil;
import com.swang.pms.common.util.LoggerUtil;
import com.swang.pms.model.annotation.PltLog;
import com.swang.pms.model.common.Pager;
import com.swang.pms.model.dto.ManageMenuDto;
import com.swang.pms.model.entity.CurrentKey;
import com.swang.pms.model.entity.ManageMenu;
import com.swang.pms.model.entity.ManageUser;
import com.swang.pms.model.enums.Status;
import com.swang.pms.model.vo.ResultMessage;
import com.swang.pms.service.manage.ManageMenuService;
import com.swang.pms.service.manage.ManageRoleService;
import com.swang.pms.web.controller.BaseController;

/**
 * @ClassName: ManageMenuController
 * @Description: 菜单服务控制层
 * @author 王泽
 * @date 2017年3月16日 下午9:45:51
 */
@Controller
@RequestMapping("/manageMenu")
public class ManageMenuController extends BaseController {

    private static final Logger LOGGER = Logger.getLogger(ManageMenuController.class);

    @Resource
    ManageRoleService           manageRoleService;
    @Resource
    ManageMenuService           manageMenuService;

    /*
     * @Resource OssUtil ossUtil;
     * @Value("#{bucketMap['oss.MEDICAL_PF_PROD']}") private String
     * MEDICAL_PF_PROD;
     * @Value("#{bucketMap['oss.KEY_PREFIX']}") private String OSS_KEY_PREFIX;
     */

    @RequestMapping(value = "/page")
    public String page(ModelMap model) {
        String statusComboData = EnumToDataUtil.getDHEnumsValuesFromEnum(Status.class);
        model.put("statusComboData", statusComboData);
        return "sys/pageManageMenu";
    }

    @RequestMapping(value = "/editMenu")
    public String editMenu(ModelMap model, @RequestParam("type") String type) {
        model.put("type", type);
        return "sys/win/editManageMenu";
    }

    @PltLog(log = "查询菜单")
    @RequestMapping(value = "/findPageData")
    public @ResponseBody Pager findPageData(@ModelAttribute Pager page, @ModelAttribute ManageMenuDto dto) {
        Pager resultPage = new Pager();
        try {
            if (dto != null && StringUtils.isNotBlank(dto.getMenuName())) {
                dto.setMenuName(dto.getMenuName().replaceAll("%", "\\\\%"));
            }
            resultPage = this.manageMenuService.findPageDataByDto(page, dto);
        } catch (Exception e) {
            resultPage.change(false, "查询失败: " + e.getMessage());
            LoggerUtil.error(LOGGER, "manageMenu-findPageData error: {0}", e.getMessage());
        }
        return resultPage;
    }

    @PltLog(log = "新增菜单")
    @RequestMapping(value = "/add")
    public @ResponseBody ResultMessage add(ManageMenu menu, MultipartHttpServletRequest multipartRequest, HttpServletRequest request) {
        ResultMessage result = new ResultMessage(true, "新增成功");
        CurrentKey currentKey = new CurrentKey();
        currentKey.setId(menu.getRandomNum());
        try {
            if (!checkParam(request, currentKey)) {
                result.change(false, "水平访问受限，请刷新当前页面再试!");
                return result;
            }
            for (Iterator<String> it = multipartRequest.getFileNames(); it.hasNext();) {
                String name = it.next();
                MultipartFile imgFile = multipartRequest.getFile(name);
                if (!checkAndUploadImg(menu, imgFile, result)) {
                    return result;
                }
            }
            if (StringUtils.isEmpty(menu.getPictureUrl())) {
                result.change(false, " 图标不能为空");
                return result;
            }
            ManageUser admin = getSessionUser(request);
            menu.setOperator(admin.getUserName());
            menu.setOperator(admin.getUserName());
            menu.setGmtCreate(new Date());
            menu.setGmtModify(new Date());
            if (StringUtils.isBlank(menu.getStatus())) {
                menu.setStatus(Status.ENABLED.getCode());
            }
            if (this.manageMenuService.getManageMenuCount(menu) > 0) {
                result.change(false, "存在id为【" + menu.getId() + "】的记录！");
                return result;
            }
            this.manageMenuService.addManageMenu(menu);
        } catch (Exception e) {
            result.change(false, "保存失败 , 错误信息:" + e.getMessage());
        }
        return result;
    }

    @PltLog(log = "编辑菜单")
    @RequestMapping(value = "/update")
    public @ResponseBody ResultMessage update(ManageMenu menu, MultipartHttpServletRequest multipartRequest, HttpServletRequest request) {
        ResultMessage result = new ResultMessage(true, "编辑成功");
        CurrentKey currentKey = new CurrentKey();
        currentKey.setId(menu.getRandomNum());
        try {
            if (!checkParam(request, currentKey)) {
                result.change(false, "水平访问受限，请刷新当前页面再试!");
                return result;
            }
            for (Iterator<String> it = multipartRequest.getFileNames(); it.hasNext();) {
                String name = it.next();
                MultipartFile imgFile = multipartRequest.getFile(name);
                if (!checkAndUploadImg(menu, imgFile, result)) {
                    return result;
                }
            }
            menu.setGmtModify(new Date());
            if (!menu.getId().equals(menu.getOldId())) {
                if (this.manageMenuService.getManageMenuCount(menu) > 0) {
                    result.change(false, "存在id为【" + menu.getId() + "】的记录！");
                    return result;
                }
            }
            this.manageMenuService.updateManageMenuByKeySelective(menu);
        } catch (Exception e) {
            result.change(false, "保存失败 , 错误信息:" + e.getMessage());
            LoggerUtil.error(LOGGER, "manageMenu-update error: {0}", e.getMessage());
        }
        return result;
    }

    private boolean checkAndUploadImg(ManageMenu menu, MultipartFile imgFile, ResultMessage result) throws Exception {
        return true;
    }

    @PltLog(log = "更改菜单状态")
    @RequestMapping(value = "/changeState")
    public @ResponseBody ResultMessage changeState(ManageMenu menu, HttpServletRequest request) {
        ResultMessage result = new ResultMessage(true, "成功");
        if (menu.getId() == null) {
            result.change(false, "参数中id为空");
            return result;
        }
        CurrentKey currentKey = new CurrentKey();
        currentKey.setId(menu.getId());
        if (!checkParam(request, currentKey)) {
            result.change(false, "水平访问受限，请刷新当前页面再试!");
            return result;
        }
        if (StringUtils.isBlank(menu.getStatus())) {
            menu.setStatus(Status.DISABLED.getCode());
        }
        menu.setGmtModify(new Date());
        menu.setOldId(menu.getId());
        try {
            this.manageMenuService.updateManageMenuByKeySelective(menu);
        } catch (Exception e) {
            result.change(false, "删除失败,错误信息:" + e.getMessage());
            LoggerUtil.error(LOGGER, "manageMenu-changeState error: {0}", e.getMessage());
        }
        return result;
    }

}
